package com.semidata.rtd.core.http.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import com.semidata.rtd.core.service.Service;
import com.semidata.rtd.core.service.ServiceException;

public class HttpService implements Service {

	private int port;
	private int threads;
	private EventLoopGroup bossGroup;
	private EventLoopGroup workerGroup;
	private Channel ch;
	private HttpDispatcher dispatcher;
	
	public HttpService(int port, int threads, HttpDispatcher dispatcher) {
		this.port = port;
		this.threads = threads;
		this.dispatcher = dispatcher;
	}
	
	@Override
	public void start() {
		try {
			bossGroup = new NioEventLoopGroup(1);
			workerGroup = new NioEventLoopGroup(threads);

			ServerBootstrap b = new ServerBootstrap();
			b.group(bossGroup, workerGroup)
					.channel(NioServerSocketChannel.class)
					.childHandler(new HttpServiceInitializer(dispatcher));
			ch = b.bind(port).sync().channel();
			
		} catch (InterruptedException e) {
			throw new ServiceException(e);
		} 
	}

	@Override
	public void stop() {
		ch.close();
		try {
			ch.closeFuture().sync();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
	}
}
